package com.lry.basic.mq;


import java.util.UUID;

/**
 * Created by Administrator on 2017/5/29.
 */

public class TestHandler {
    public static void main(String[]args){
        //消息机制不光光是更新ui的，最准确地来说是通信的，因为我可以放在ui线程执行也可以放在子线程
        new Thread(){
            @Override
            public void run() {
                Looper.prepare();
                final Handler handler=new Handler(){
                    @Override
                    public void handlerMessage(Message msg) {
                        System.out.println(Thread.currentThread().getName() + "   receiver:"+msg.toString());
                    }
                };
                for(int i=0;i<10;i++) {//多线程跑测试自己的handler是不是线程安全的，结果发现是的
                    new Thread() {
                        @Override
                        public void run() {
                            while (true) {
                                try {
                                    Thread.sleep(1000);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                Message msg = new Message();
                                //多线程一起跑randomUUID要加个锁
                                synchronized (UUID.class){
                                    msg.msg = UUID.randomUUID().toString();
                                }

                                System.out.println(Thread.currentThread().getName() + "    send:" + msg.toString() + "    ");
                                handler.sendMessage(msg);
                            }
                        }
                    }.start();
                }
                Looper.loop();
            }
        }.start();


    }
}
